﻿Public Class ConnectionSAS
    Implements IConnection

    Private m_obObjectFactory As SASObjectManager.ObjectFactory
    Private m_obSAS As SAS.Workspace
    Private m_obObjectKeeper As SASObjectManager.ObjectKeeper

    Private m_ConnectionSAS As OleDb.OleDbConnection
    Public ReadOnly Property Connection As System.Data.OleDb.OleDbConnection Implements IConnection.Connection
        Get
            If m_ConnectionSAS Is Nothing Then
                Workspace_Initialize()
            End If
            Return m_ConnectionSAS
        End Get
    End Property

    ''' <summary>
    ''' Création de l'espace de travail et de la connection sur cet espace de travail
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Workspace_Initialize()
        'Création de la connection faisant référence à l'espace de travail
        'de l'objet
        m_obObjectFactory = New SASObjectManager.ObjectFactory
        'Etablissement d'un espace de travail SAS 
        m_obSAS = m_obObjectFactory.CreateObjectByServer _
                ("MaSession", True, Nothing, "", "")
        m_obObjectKeeper = New SASObjectManager.ObjectKeeper()
        m_obObjectKeeper.AddObject(1, "MaSession", m_obSAS)
        m_ConnectionSAS = New OleDb.OleDbConnection()
        m_ConnectionSAS.ConnectionString = "Provider=sas.IOMProvider.1;SAS Workspace ID=" & CType(m_obSAS, SAS.Workspace).UniqueIdentifier
    End Sub

    ''' <summary>
    ''' Envoie une DataTable vers une table SAS
    ''' </summary>
    ''' <param name="Data"></param>
    ''' <param name="NomTableDansBDD"></param>
    ''' <remarks></remarks>
    Public Sub SendData(Data As DataTable, NomTableDansBDD As String) Implements IConnection.SendData

        'Prend les données en entrée et les transfère vers un FILENAME SAS XML. 
        'Le XML est ensuite intégré dans une table SAS.
        Dim inputDS, TempDS As DataSet
        Dim ATempDS As Boolean
        Dim obFileref As SAS.Fileref
        Dim assignedName As String = ""
        ' Filename websvc TEMP;

        'Intégration de la DataTable dans le DataSet à exporter sous XML  (il ne doit y avoir qu'une seule table dans le dataSet)
        ATempDS = False
        TempDS = New DataSet
        inputDS = New DataSet
        If Not Data.DataSet Is Nothing Then
            ATempDS = True
            TempDS = Data.DataSet
            TempDS.Tables.Remove(Data)
        End If
        inputDS.Tables.Add(Data)

        'Création du XML dans obFileref. assignedName est passé en référence et contient le nom du Filename une fois assigné.
        obFileref = m_obSAS.FileService.AssignFileref("TblXML", "TEMP", "", "", assignedName)
        ''obFileref = m_obSAS.FileService.AssignFileref("TblXML", "DISK", "C:\pti\travail\omane\07_CalculsIntermediaires\Test.xml", "", assignedName)

        Dim obTextStream As SAS.TextStream
        obTextStream = obFileref.OpenTextStream(
        SAS.StreamOpenMode.StreamOpenModeForWriting, 2000)
        obTextStream.Separator = " "
        obTextStream.Write("<?xml version=""1.0"" standalone=""yes"" ?>")
        obTextStream.Write(inputDS.GetXml())
        obTextStream.Close()

        ' An ADO.Net data set is capable of holding multiple tables, schemas,
        ' and relationships. This sample assumes that the ADO.Net data set
        ' only contains a single table whose name and columns fit within SAS
        ' naming rules. This would be an ideal location to use XMLMap to
        ' transform the schema of the provided data set into something that
        ' SAS may prefer.
        ' Here, the default mapping is used. Note that the LIBNAME statement
        ' uses the fileref of the same name because we did not specify a file.
        ' Using the IOM method is cleaner than using the Submit because an
        ' error is returned if there is a problem making the assignment
        m_obSAS.DataService.AssignLibref("TblXML", "XML", "", "")
        ''m_obSAS.DataService.AssignLibref("TblXML", "XML", "C:\pti\travail\omane\07_CalculsIntermediaires\Test.xml", "")
        ' obSAS.LanguageService.Submit("libname webSvc XML;")

        'Depuis la librairie venant d'être assignée, procéder à l'export de la table xml vers le répertoire de sortie.
        'obLibRef = obSAS.DataService.AssignLibref("Dskt", "", "C:\pti\travail\omane\08_Sorties", "")
        'obSAS.LanguageService.Submit("data Dsktop.TOTO;" & vbCrLf & _
        '                             "set WebSvc;" & vbCrLf & _
        '                             "run;")
        m_obSAS.LanguageService.Submit("data " & NomTableDansBDD & ";" & vbCrLf & _
                                       "set TblXML." & Data.TableName & ";" & vbCrLf & _
                                       "run;")

        'Désassignation du LIBNAME et du FILENAME liés au fichier de transfert XML.
        m_obSAS.DataService.DeassignLibref("TblXML")
        m_obSAS.FileService.DeassignFileref(assignedName)

        'Si la table était dans un Dataset on l'y remet
        inputDS.Tables.Remove(Data)
        If ATempDS Then
            TempDS.Tables.Add(Data)
        End If
    End Sub

    ''' <summary>
    ''' Fermeture de la connection et suppression de l'espace de travail
    ''' </summary>s
    ''' <remarks></remarks>
    Public Sub Workspace_Dispose() Implements IConnection.Dispose
        If Not m_obObjectKeeper Is Nothing Then
            m_obObjectKeeper.RemoveAllObjects()
        End If
        If Not m_ConnectionSAS Is Nothing Then
            If m_ConnectionSAS.State = ConnectionState.Open Then m_ConnectionSAS.Close()
        End If
        m_obSAS.Close()
        m_ConnectionSAS = Nothing
        m_obSAS = Nothing
        m_obObjectFactory = Nothing
    End Sub

    ''' <summary>
    ''' Ajout d'une librairie dans l'espace de travail
    ''' </summary>s
    ''' <remarks></remarks>
    Public Sub SAS_assigneLibName(ByVal nomDossierConnection As String, _
                                       ByVal nomLibrairie As String) Implements IConnection.AssignLibName
        If m_ConnectionSAS Is Nothing Then
            Workspace_Initialize()
        End If
        Dim obLibRef As Object = m_obSAS.DataService.AssignLibref(nomLibrairie, "", nomDossierConnection, "")
    End Sub

    Public Sub ExecuteStoredProcess(NomDossier As String, NomProgramme As String, Parametres As String) Implements IConnection.ExecuteStoredProcess
        'Remplacer le nom du dossier par String
        'Dans le nom du dossier, rechercher la première occurence du ":" et remplacer ce qu'il y a à gauche par file

        Dim NomRepository As String = String.Concat("file", Right(NomDossier, Len(NomDossier) - NomDossier.IndexOf(":")))
        'Définition du répertoire contenant le processus stocké à exécuter
        m_obSAS.LanguageService.StoredProcessService.Repository = NomRepository
        'm_obSAS.LanguageService.StoredProcessService.Repository = "file:/pti/travail/omane/06_Referentiel"
        'm_obSAS.LanguageService.StoredProcessService.Execute("CalculTxGarEqTarifaire", "Param1=one Param2=two")

        m_obSAS.LanguageService.StoredProcessService.Execute(NomProgramme, Parametres)
    End Sub
End Class
